<% # This script is used to authenticate the user in the subforum iframe %>
<% # Could be moved to a separate file with some re-factoring %>
<% default_url_component = RequestStore.store[:subforem_id] == RequestStore.store[:default_subforem_id] ? "#{URL.protocol}#{RequestStore.store[:root_subforem_domain]}" : "#{URL.protocol}#{RequestStore.store[:default_subforem_domain]}" %>
<script>
  var userSignedIn = <%= user_signed_in? %>;
  if (document.readyState === 'complete' || document.readyState === 'interactive') {
    initAuth();
  } else {
    document.addEventListener('DOMContentLoaded', initAuth);
  }

  function initAuth() {
    var paramToken = new URLSearchParams(window.location.search).get('jwt');

    if (paramToken && !userSignedIn) {
      authenticateUser(paramToken);
    } else {
      var iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      iframe.src = '<%= default_url_component unless user_signed_in? %>/auth_pass/iframe';
  
      document.body.appendChild(iframe);
  
      window.addEventListener('message', function(event) {
        if (event.origin !== '<%= default_url_component %>' && event.origin !== window.location.origin) {
          return;
        }
  
        var data = event.data;
  
        if (data.authenticated && !userSignedIn) {
          authenticateUser(data.token);
        } else if(data.authenticated && window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
          window.ReactNativeWebView.postMessage(JSON.stringify({
            action: 'login',
            token: data.token,
          }));
        }
      });  
    }

    function authenticateUser(token) {
      fetch('/auth_pass/token_login', {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRF-Token': getMetaContent('csrf-token'),
        },
        body: JSON.stringify({ token: token }),
      })
      .then(function(response) {
        return response.json();
      })
      .then(function(data) {
        if (data.success) {
          if (document.head.querySelector('meta[name="user-signed-in"][content="false"]')) {
            // Reload the page to update the user's state
            location.reload();
          }
        }
      })
      .catch(function(error) {
        console.error('Error during authentication:', error);
      });
    }

    function getMetaContent(name) {
      var element = document.querySelector('meta[name="' + name + '"]');
      return element ? element.getAttribute('content') : '';
    }
  }
</script>
